import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
} from 'react-native';
import {init, Geolocation, stop} from 'react-native-amap-geolocation';
import {formatTimestampToDateTime} from '../utils';

const App = () => {
  const [location, setLocation] = useState(null);
  const [address, setAddress] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isWatching, setIsWatching] = useState(false);
  const [error, setError] = useState(null);

  // 初始化高德地图定位服务
  useEffect(() => {
    const initLocationService = async () => {
      try {
        // 初始化配置（请替换为您自己的高德地图Key）
        await init('07c5ecf4444b8f82312a678d5f36959a');
      } catch (err) {
        console.error('初始化失败:', err);
        setError('初始化定位服务失败，请检查配置');
      }
    };

    initLocationService();
  }, []);

  // 获取当前位置
  const getCurrentLocation = async () => {
    setIsLoading(true);
    setError(null);

    try {
      Geolocation.getCurrentPosition(res => {
        if (res) {
          setLocation(res.location);
          setAddress(res.location?.address);
          setIsLoading(false);
          console.log('res', JSON.stringify(res.location));
        } else {
          setError('获取位置信息失败！！');
        }
      });
    } catch (err) {
      console.error('获取位置失败:', err);
      setError(`获取位置失败: ${err.message || err}`);
      setIsLoading(false);
    }
  };
  // 开始持续定位
  const startWatchingLocation = async () => {
    setIsLoading(true);
    setError(null);
    try {
      // 开始监听位置变化
      Geolocation.watchPosition(
        position => {
          setLocation(position.location);
          setAddress(position.location?.address);
          setIsWatching(true);
          setIsLoading(false);
        },
        err => {
          console.error('持续定位失败:', err);
          setError(`持续定位失败: ${err.message || err}`);
          setIsLoading(false);
          setIsWatching(false);
        },
      );
    } catch (err) {
      console.error('开始持续定位失败:', err);
      setError(`开始持续定位失败: ${err.message || err}`);
      setIsLoading(false);
    }
  };

  // 停止持续定位
  const stopWatchingLocation = () => {
    stop();
    setIsWatching(false);
  };

  // 清除位置信息
  const clearLocation = () => {
    setLocation(null);
    setAddress(null);
    setError(null);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.header}>高德地图定位示例</Text>

      <View style={styles.buttonContainer}>
        <TouchableOpacity
          style={[styles.button, styles.primaryButton]}
          onPress={getCurrentLocation}
          disabled={isLoading || isWatching}>
          <Text style={styles.buttonText}>获取当前位置</Text>
        </TouchableOpacity>

        {!isWatching ? (
          <TouchableOpacity
            style={[styles.button, styles.secondaryButton]}
            onPress={startWatchingLocation}
            disabled={isLoading}>
            <Text style={styles.buttonText}>开始持续定位</Text>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity
            style={[styles.button, styles.stopButton]}
            onPress={stopWatchingLocation}>
            <Text style={styles.buttonText}>停止持续定位</Text>
          </TouchableOpacity>
        )}

        <TouchableOpacity
          style={[styles.button, styles.clearButton]}
          onPress={clearLocation}>
          <Text style={styles.buttonText}>清除位置</Text>
        </TouchableOpacity>
      </View>

      {isLoading && (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#1890ff" />
          <Text style={styles.loadingText}>定位中...</Text>
        </View>
      )}

      {error && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

      {location && (
        <ScrollView style={styles.locationContainer}>
          <Text style={styles.sectionTitle}>位置信息</Text>

          <View style={styles.infoRow}>
            <Text style={styles.label}>经度:</Text>
            <Text style={styles.value}>{location.longitude}</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.label}>纬度:</Text>
            <Text style={styles.value}>{location.latitude}</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.label}>精度:</Text>
            <Text style={styles.value}>{location.accuracy} 米</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.label}>海拔:</Text>
            <Text style={styles.value}>{location.altitude || 'N/A'} 米</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.label}>速度:</Text>
            <Text style={styles.value}>{location.speed || '0'} m/s</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.label}>方向:</Text>
            <Text style={styles.value}>{location.heading || '0'}°</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.label}>定位时间:</Text>
            <Text style={styles.value}>
              {location?.timestamp
                ? `${formatTimestampToDateTime(location?.timestamp)}`
                : 'N/A'}
            </Text>
          </View>

          <Text style={[styles.sectionTitle, {marginTop: 20}]}>地址信息</Text>

          <View style={styles.addressContainer}>
            <Text style={styles.addressText}>{address || '无地址信息'}</Text>
          </View>

          {location.country && (
            <View style={styles.infoRow}>
              <Text style={styles.label}>国家:</Text>
              <Text style={styles.value}>{location.country}</Text>
            </View>
          )}

          {location.province && (
            <View style={styles.infoRow}>
              <Text style={styles.label}>省份:</Text>
              <Text style={styles.value}>{location.province}</Text>
            </View>
          )}

          {location.city && (
            <View style={styles.infoRow}>
              <Text style={styles.label}>城市:</Text>
              <Text style={styles.value}>{location.city}</Text>
            </View>
          )}

          {location.district && (
            <View style={styles.infoRow}>
              <Text style={styles.label}>区县:</Text>
              <Text style={styles.value}>{location.district}</Text>
            </View>
          )}

          {location.street && (
            <View style={styles.infoRow}>
              <Text style={styles.label}>街道:</Text>
              <Text style={styles.value}>{location.street}</Text>
            </View>
          )}

          {location.streetNumber && (
            <View style={styles.infoRow}>
              <Text style={styles.label}>门牌号:</Text>
              <Text style={styles.value}>{location.streetNumber}</Text>
            </View>
          )}
        </ScrollView>
      )}

      {!location && !isLoading && !error && (
        <View style={styles.placeholder}>
          <Text style={styles.placeholderText}>点击上方按钮获取位置信息</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 16,
    paddingTop: 40,
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
    color: '#1890ff',
  },
  buttonContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginBottom: 20,
  },
  button: {
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 8,
    marginBottom: 10,
    minWidth: '48%',
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  primaryButton: {
    backgroundColor: '#1890ff',
  },
  secondaryButton: {
    backgroundColor: '#52c41a',
  },
  stopButton: {
    backgroundColor: '#ff4d4f',
  },
  clearButton: {
    backgroundColor: '#faad14',
    minWidth: '100%',
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 16,
  },
  loadingContainer: {
    alignItems: 'center',
    padding: 20,
  },
  loadingText: {
    marginTop: 10,
    color: '#666',
  },
  errorContainer: {
    backgroundColor: '#fff2f0',
    borderColor: '#ffccc7',
    borderWidth: 1,
    borderRadius: 8,
    padding: 16,
    marginBottom: 20,
  },
  errorText: {
    color: '#f5222d',
    textAlign: 'center',
  },
  locationContainer: {
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 16,
    marginBottom: 20,
    maxHeight: 400,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 12,
    color: '#333',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    paddingBottom: 8,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  label: {
    fontWeight: 'bold',
    color: '#666',
    width: '30%',
  },
  value: {
    flex: 1,
    textAlign: 'right',
    color: '#333',
  },
  addressContainer: {
    backgroundColor: '#e6f7ff',
    borderRadius: 8,
    padding: 12,
    marginVertical: 10,
  },
  addressText: {
    fontSize: 16,
    color: '#1890ff',
    lineHeight: 24,
  },
  placeholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  placeholderText: {
    fontSize: 18,
    color: '#999',
    textAlign: 'center',
  },
});

export default App;
